//
//  WBStatusViewModel.swift
//  weibo
//
//  Created by iobit on 2017/07/06.
//  Copyright © 2017 zhuxu. All rights reserved.
//

import Foundation

/// 单条微博的视图的模型
class WBStatusViewModel: CustomStringConvertible {
    // 微博模型
    var status: WBStatus
    
    // 会员图标 - 存储型属性（用内存换cpu）
    var memberIcon: UIImage?
    
    // 认证类型，-1：没有认证，0：认证， 2、3、5企业认证，220：达人
    var vipIcon: UIImage?
    
    /// 转发
    var retweetStr: String?
    /// 评论
    var commentStr: String?
    /// 点赞
    var likeStr: String?
    
    /// 视图模型size
    var pictureViewSize = CGSize()
    
    
    var pic_urls: [WBStatusPicture]?
    
    /// 构造函数
    ///
    /// - Parameter model: 微博模型
    /// - returns: 微博的视图模型
    init(model: WBStatus) {
        
        self.status = model
        
        //直接计算出会员图标
        if (model.user?.mbrank)! > 0 && (model.user?.mbrank)! < 7 {
            let imageName = "common_icon_membership_level\(model.user?.mbrank ?? 1)"
            memberIcon = UIImage(named: imageName)
        }
        
        // vip认证
        switch model.user?.verified_type ?? -1 {
        case 0:
            vipIcon = UIImage(named: "avatar_vip")
        case 1,2,3,5:
            vipIcon = UIImage(named: "avatar_enterprise_vip")
        case 220:
            vipIcon = UIImage(named: "avatar_grassroot")
        default:
            break
        }
        
        retweetStr = countString(count: model.reposts_count, defalutStr: "转发")
        commentStr = countString(count: model.comments_count, defalutStr: "评论")
        likeStr = countString(count: model.attitudes_count, defalutStr: "赞")
        
        
        pictureViewSize = calcPictureViewSize(count: model.pic_urls?.count)
        
    }
    
    /// 计算指定数量的图片对应的配图视图的大小
    ///
    /// - Parameter count: 配图数量
    /// - Returns: 配图视图大小
    private func calcPictureViewSize(count: Int?)->CGSize {
    
        if count == 0 || count == nil{
            return CGSize()
        }
        


        let row = CGFloat((count! - 1)/3 + 1)
        
        let height = WBStatusPictureViewOutterMargin + row * WBStatusPictureViewItemWidth + (row - 1) * WBStatusPictureViewInnerMargin
        
        return CGSize(width: WBStatusPictureViewWidth, height: height)
    }
    
    
    /// 给一个数字，返回对应的描述结果
    ///
    /// - Parameters:
    ///   - count: 数字
    ///   - defalutStr: 默认文字
    /// - Returns: 描述结果
    private func countString(count: Int, defalutStr: String) -> String {
        
        if count == 0 {
            return defalutStr
        }
        
        if count < 10000 {
            return count.description
        }
        // 大于10000，显示为X.XX万
        return String(format: "%.02f 万", Double(count)/10000)

    }
    
    
    var description: String {
        return status.description
    }
}
